package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝
 */
@Service
public class AlipayServiceImpl implements AlipayService {


    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AlipayClient alipayClient;

    //统一收单下单并支付页面接口
    @Override
    public String submit(Long orderId) {
        //1:先查询支付表是否存在了 如果不存在 保存支付表（部分信息）   幂等性问题  如果存在了 修改支付方式时间  再 返回
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentType.ALIPAY);
        //2：支付宝对外暴露接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOutTradeNo());
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("total_amount", paymentInfo.getTotalAmount().toString());
        map.put("subject", paymentInfo.getSubject());
        request.setBizContent(JSONObject.toJSONString(map));
        //设置同步回调的路径
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步回调的路径
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
        }
        //3:将支付宝同步回调
        return response.getBody();
    }
}
